//
//  RYCImagePageView.m
//  Locoso
//
//  Created by zhiwei ma on 12-10-23.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RYCImagePageView.h"

@interface RYCImagePageView ()
@property (nonatomic, retain) UIScrollView* scrollView;
@property (nonatomic, retain) UIPageControl* pageControl;
@property (nonatomic, retain) NSTimer* timer;
- (NSInteger)numberOfPages;
- (void)startTimer;
- (void)stopTimer;
- (void)loadScrollContentViewForLoop:(NSInteger)aCurrentIndex;

@property (nonatomic, retain) UIColor* pageCtrlBGColor;
@end

@implementation RYCImagePageView
@dynamic currentPage;
@synthesize timer = _timer;
@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;
@synthesize pageCtrlBGColor = _pageCtrlBGColor;
@synthesize imageViews = _imageViews;
@synthesize scrollType = _scrollType;
@synthesize timeInterval = _timeInterval;

- (id)initWithFrame:(CGRect)frame scrollType:(RYCPageViewScrollType)aType delegate:(id)aDelegate
{    self = [super initWithFrame:frame];
    if (self)
    {
        _scrollDirection = 0;
        _scrollType  = RYCPageViewScrollType_Swing;
        _state = RYCPageViewState_Stop;
        _timeInterval = 3.5;
        _scrollType = aType;
        _delegate = aDelegate;
    }
    return self;
}

- (void)dealloc
{
    self.pageCtrlBGColor = nil;
    self.imageViews = nil;
    [super dealloc];
}

- (NSInteger)currentPage
{
    return _pageControl.currentPage;
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    _pageControl.currentPage = currentPage;
}

- (void)setImageViews:(NSArray *)aImageViews
{
    if (nil == aImageViews || aImageViews.count == 0)
    {
        [_imageViews release];
        
        [_scrollView removeFromSuperview];
        self.scrollView = nil;
        
        [_pageControl removeFromSuperview];
        self.pageControl = nil;
        return;
    }
    
    if (nil == _scrollView)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        [self addSubview:_scrollView];
        
        UITapGestureRecognizer* tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapGesture:)] autorelease];
        tapGesture.numberOfTapsRequired = 1;
        [_scrollView addGestureRecognizer:tapGesture];
    }
    
    [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    if (_imageViews)
    {
        [_imageViews release];
    }
    
    _imageViews = [NSArray arrayWithArray:aImageViews];
    [_imageViews retain];
    
    //个数不足3，强制修改滚动方式
//    if (RYCPageViewScrollType_Loop == _scrollType
//        && [_imageViews count] < 3)
//    {
//        _scrollType = RYCPageViewScrollType_Swing;
//    }

    if (RYCPageViewScrollType_Swing == _scrollType)
    {        
        CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
        for (UIImageView* imgv in _imageViews)
        {
            imgv.center = center;
            [_scrollView addSubview:imgv];
            center.x += _scrollView.bounds.size.width;
        }
        _scrollView.contentSize = CGSizeMake(_scrollView.bounds.size.width * self.numberOfPages, _scrollView.bounds.size.height);
        _scrollView.contentOffset = CGPointZero;
    }
    else if (RYCPageViewScrollType_Loop == _scrollType) 
    {
        [self loadScrollContentViewForLoop:0];
    }
    
    if (_pageControl)
    {
        [_pageControl removeFromSuperview];
        self.pageControl = nil;
    }
    
    UIPageControl* pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 15, self.bounds.size.width, 15)];
    pageCtrl.hidesForSinglePage = YES;
    pageCtrl.userInteractionEnabled = NO;
    if (nil == _pageCtrlBGColor)
    {
        pageCtrl.backgroundColor = [UIColor blackColor];
    }
    else
    {
        pageCtrl.backgroundColor = self.pageCtrlBGColor;
    }
    pageCtrl.alpha = 0.5;
    pageCtrl.numberOfPages = [_imageViews count];
    pageCtrl.currentPage = 0;
    [self addSubview:pageCtrl];
    self.pageControl = pageCtrl;
    [pageCtrl release];
}

- (void)setPageControlBgColor:(UIColor*)aColor
{
    self.pageCtrlBGColor = aColor;
    _pageControl.backgroundColor = aColor;
}

- (void)startAutoScroll
{
    [self stopTimer];
    
    if ([_imageViews count] < 2)
    {
        return;
    }
    
    [self startTimer];
    _state = RYCPageViewState_Start;
}

- (void)pauseAutoScroll
{
    [self stopTimer];
    _state = RYCPageViewState_Pause;
}

- (void)stopAutoScroll
{
    [self stopTimer];
    _state = RYCPageViewState_Stop;
}

- (void)stopAndClearDelegate
{
    _delegate = nil;
    [self stopAutoScroll];
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    NSLog(@"%s", __FUNCTION__);
    [self pauseAutoScroll];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    NSLog(@"%s", __FUNCTION__);
    CGPoint offset = _scrollView.contentOffset;
//    NSLog(@"offset+++++ x=%.2f y=%.2f",offset.x, offset.y);
    NSInteger offsetPage = offset.x / _scrollView.bounds.size.width;
    NSInteger maxPage = self.numberOfPages - 1;
    
    if (RYCPageViewScrollType_Swing == _scrollType)
    {
        self.currentPage = offsetPage;
    }
    else if (RYCPageViewScrollType_Loop == _scrollType)
    {
        UIImageView* imgv = [_scrollView.subviews objectAtIndex:offsetPage];
        NSInteger currentIndexInImageViews = [_imageViews indexOfObject:imgv];
        
        if (offsetPage == maxPage)
        {
            [self loadScrollContentViewForLoop:currentIndexInImageViews];
        }
        else if (0 == offsetPage)
        {
            [self loadScrollContentViewForLoop:currentIndexInImageViews];
        }
        self.currentPage = currentIndexInImageViews;
    }
    
    if (RYCPageViewState_Pause == _state)
    {
        [self startTimer];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    CGPoint offset = _scrollView.contentOffset;
    NSInteger offsetPage = offset.x / _scrollView.bounds.size.width;
    NSInteger maxPage = self.numberOfPages - 1;

    if (RYCPageViewScrollType_Swing == _scrollType)
    {
        self.currentPage = offsetPage;
    }
    else if (RYCPageViewScrollType_Loop == _scrollType)
    {
        UIImageView* imgv = [_scrollView.subviews objectAtIndex:offsetPage];
        NSInteger currentIndexInImageViews = [_imageViews indexOfObject:imgv];
        if (offsetPage == maxPage)
        {
            [self loadScrollContentViewForLoop:currentIndexInImageViews];
        }
        self.currentPage = currentIndexInImageViews;
    }
}

#pragma mark private
//aCurrentIndex 在_imageViews中的索引
- (void)loadScrollContentViewForLoop:(NSInteger)aCurrentIndex
{
    [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSInteger maxIndex = self.numberOfPages - 1;
    NSRange range1, range2;
    UIImageView* imgv = nil;
    
    if (0 == aCurrentIndex)
    {
        range1 = NSMakeRange(maxIndex, 1);
        range2 = NSMakeRange(0, maxIndex);
    }
    else
    {
        range1 = NSMakeRange(aCurrentIndex - 1, maxIndex - aCurrentIndex + 1 + 1);
        range2 = NSMakeRange(0, aCurrentIndex - 1);
    }
    
    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    for (NSInteger i = 0; i < range1.length; i++)
    {
        imgv = [_imageViews objectAtIndex:i + range1.location];
        imgv.center = center;
        [_scrollView addSubview:imgv];
        center.x += self.bounds.size.width;
    }
    for (NSInteger j = 0; j < range2.length; j++)
    {
        imgv = [_imageViews objectAtIndex:j + range2.location];
        imgv.center = center;
        [_scrollView addSubview:imgv];
        center.x += self.bounds.size.width;
    }
    CGSize contentsize = CGSizeMake(_scrollView.bounds.size.width * self.numberOfPages, _scrollView.bounds.size.height);
    _scrollView.contentSize = contentsize;
    if (self.numberOfPages < 3)
    {
        _scrollView.contentOffset = CGPointZero;
    }
    else
    {
        _scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
    }
}

- (NSInteger)numberOfPages
{
    return [_imageViews count];
}

- (void)startTimer
{        
    self.timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(didTimer:) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    if (_timer)
    {
        [_timer invalidate];
        self.timer = nil;
    }
}

- (void)didTapGesture:(UITapGestureRecognizer*)aGesture
{
    if (1 == aGesture.numberOfTapsRequired)
    {
        if (_delegate && [_delegate respondsToSelector:@selector(didTapAtPage:pageIndex:)])
        {
            [_delegate didTapAtPage:self pageIndex:self.currentPage];
        }
    }
}

- (void)didTimer:(id)userInfo
{
//    NSLog(@"%s", __FUNCTION__);
    CGPoint offset = _scrollView.contentOffset;
//    NSLog(@"%U",self);
//    NSLog(@"dst offset.x= %.2f",offset.x);
    NSInteger offsetPage = offset.x / _scrollView.bounds.size.width;
    NSInteger maxPage = self.numberOfPages - 1;
    
    if (RYCPageViewScrollType_Swing == _scrollType)
    {
        if (0 == _scrollDirection)
        {
            if (self.currentPage < self.numberOfPages - 1)
            {
                offset.x += _scrollView.bounds.size.width;
            }
            else
            {
                _scrollDirection = 1;
                offset.x -= _scrollView.bounds.size.width;
            }
        }
        else
        {
            if (self.currentPage > 0)
            {
                offset.x -= _scrollView.bounds.size.width;
            }
            else
            {
                _scrollDirection = 0;
                offset.x += _scrollView.bounds.size.width;
            }
        }
        [_scrollView setContentOffset:offset animated:YES];
    }
    else if (RYCPageViewScrollType_Loop == _scrollType)
    {        
//        NSAssert(offsetPage < maxPage,  @"11");
        if (offsetPage < maxPage)
        {
            offset.x += _scrollView.bounds.size.width;
            [_scrollView setContentOffset:offset animated:YES];
        }
    }
    
}
@end
